package com.region.loadbalancer.monitor.stat;

import com.region.loadbalancer.group.Server;

import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Using a socket connection to determine if a connection has been made
 *
 * @author liujieyu
 * @date 2023/5/25 23:42
 * @desciption
 */
public class SocketDetectionConnection implements DetectionConnection{

    /**
     * The default timeout is 100 milliseconds
     */
    private int timeout = 100;

    public SocketDetectionConnection() {
        this(100);
    }

    public SocketDetectionConnection(int timeout) {
        this.timeout = timeout;
    }

    @Override
    public boolean connect(Server server) {
        try (
                Socket socket = new Socket();
                ) {
            socket.connect(new InetSocketAddress(server.getHost(), server.getPort()), this.timeout);
            return true;
        } catch (Throwable throwable) {
            return false;
        }
    }
}
